#include <stdio.h>
#include <stdlib.h>
#include "tree.h"
#include "sline.h"


void insert(Tree* tree,int value)
{
    T_node* node = malloc(sizeof(T_node));
    node->data = value;
    node->left = NULL;
    node->right = NULL;

    if(tree->root == NULL)
    {
        tree->root = node;
    }
    else
    {
        T_node* tmp = tree->root;
        while (tmp != NULL)
        {
            if(value < tmp->data)
            {
                if(tmp->left == NULL)
                {
                    tmp->left = node;
                    return;
                }
                else
                {
                    tmp = tmp->left;
                }
            }
            else
            {
                if(tmp->right == NULL)
                {
                    tmp->right = node;
                    return;
                }
                else
                {
                    tmp = tmp->right;
                }                
            }
        } 
    }
}


int get_height(T_node* node)
{
    if(node == NULL)
    {
        return 0;
    }
    int left_h = get_height(node->left);
    int right_h = get_height(node->right);
    int max = (left_h > right_h)?left_h:right_h;
    return max + 1;
}


int get_maxmum(T_node* node)
{
    if(node == NULL)
    {
        return -1;
    } 
    int l1 = get_maxmum(node->left);
    int r1 = get_maxmum(node->right);
    int data = node->data;
    int max = data;
    if(l1 > max)
    {
        max = l1;
    }
    if(r1 > max)
    {
        max = r1;
    }
    return max;
}


void bstree_test(void)
{
    int arr[7] = {6,3,8,2,5,1,7};
    Tree root;
    root.root = NULL;

    for(int i = 0;i<7;i++)
    {
        insert(&root,arr[i]);
    }
    int h = get_height(root.root);
    sl_printf("h =%d \n",h);

    sl_printf("max = %d\n",get_maxmum(root.root));
    inorder(root.root);
}